package interviewQuestions;

/**
 * 字符串加法
 * 输入两个字符串a和b，字符串内容为二进制数字，求两个字符串相加的结果，
 * 加法计算方法以二进制方式计算，并返回对应的字符串结果。要求程序尽可能的高效
 *
 * */
public class StringAdd {
    public String add(String a, String b){
        int len1 = a.length() - 1;
        int len2 = b.length() - 1;
        int carry = 0;
        String result = "";
        while(len1 >= 0 && len2 >= 0){
            int v1 = len1 < 0 ? 0 : charToInt(a.charAt(len1));
            int v2 = len2 < 0 ? 0 : charToInt(b.charAt(len2));
            int sum = v1 + v2 + carry;
            carry = sum / 2;
            sum = sum % 2;
            result = String.valueOf(sum) + result;
            --len1;
            --len2;
        }
        if(carry > 0){
            result = String.valueOf(carry) + result;
        }


        return result;
    }

    // 将整数字符转为整数
    public int charToInt(char c){
        return c - '0';
    }

    //main
    public static void main(String[] args) {
        StringAdd sa = new StringAdd();
        System.out.print(sa.add("1", "1"));
    }
}
